#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>
using namespace std;
sem_t rmutex,wmutex,lockmutex;
int rc;
void*reader_p(void*id)
{
	int i=(long)id;
	sem_wait(&rmutex);
	rc++;
	printf("reader %d entered library\n",i);
	if(rc==1)
	{
		printf("reader locks the library\n");
		sem_wait(&lockmutex);
	}
	sem_post(&rmutex);
	sem_wait(&rmutex);
	rc--;
	printf("reader %d leaves library\n",i);
	if(rc==0)
	{
		printf("reader unlocks the library\n");
		sem_post(&lockmutex);
	}
	sem_post(&rmutex);
}
void*writer_p(void*id)
{
	sem_wait(&lockmutex);
	printf("writer enters into library\n");
	printf("writer doing stuff\n");
	sem_post(&lockmutex);
	printf("writer leaves and unlocks the library\n");
}
int main()
{
	pthread_t reader[3],writer;
	int j=1;
	for(int i=0;i<3;i++)
	pthread_create(&reader[i],NULL,reader_p,(void*)&i);
	
	pthread_create(&writer,NULL,writer_p,(void*)&j);
	sem_init(&rmutex,1,3);
	sem_init(&wmutex,1,0);
	sem_init(&lockmutex,1,1);
	for(int i=0;i<3;i++)
		pthread_join(reader[i],NULL);
	pthread_join(writer,NULL);
	return 0;
}
